<template>
  <div class="unity">
    <div :style="{background: 'url('+ img+') no-repeat', backgroundSize: '100% 100%', width: width, height: height}" class="canvas-style">
      <canvas id="canvas" :width="width" :height="height"/>
    </div>
  </div>
</template>

<script>

export default {
  name: 'CanvasPosition',
  props: {
    img: String,
    width: String,
    height: String,
    points: Array,
    disabled: true,
    isReset: false,
  },
  data() {
    return {
      x: '',
      y: ''
    }
  },
  watch: {
    x() {
      this._draw()
    },
    y() {
      this._draw()
    }
  },
  mounted() {
    const canvas = document.getElementById('canvas')
    // 鼠标滑过事件
    canvas.addEventListener('mousemove', event => {
      this._getMousePos(canvas, event)
    })
    // 监听点击事件
    canvas.addEventListener('click', event => {
      this._getClickPos(canvas, event)
    })
    this._draw()
  },
  methods: {
    _draw() {
      const canvas = document.getElementById('canvas')
      if (this.points && this.points.length > 0) {//有数据就画上去
        this.points.forEach(item => {
          const ctx = canvas.getContext('2d')
          ctx.beginPath()
          ctx.fillStyle = item.type ? '#03C9FF' : '#ff0000'
          ctx.strokeStyle = item.type ? '#03C9FF' : '#ff0000'
          ctx.arc(item.x, item.y, 5, 0, 2 * Math.PI) // 口(顺时针)
          ctx.fill()
          ctx.stroke()
        })
      } else {//没数据就清空
        if(this.isReset) {
          const ctx = canvas.getContext('2d')
          ctx.clearRect(0, 0, canvas.width, canvas.height)
        }
      }
    },
    // 记录鼠标位置
    _getMousePos(canvas, event) {
      const rect = canvas.getBoundingClientRect()
      this.x = event.clientX - rect.left * (canvas.width / rect.width)
      this.y = event.clientY - rect.top * (canvas.height / rect.height)
    },
    // 点击触发
    _getClickPos(canvas, event) {
      const ctx = canvas.getContext('2d')
      const rect = canvas.getBoundingClientRect()
      const x = event.clientX - rect.left * (canvas.width / rect.width)
      const y = event.clientY - rect.top * (canvas.height / rect.height)
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      if (!this.disabled) {
        ctx.beginPath()
        ctx.fillStyle = 'black'
        ctx.strokeStyle = 'black'
        // 点击的位置
        ctx.arc(x, y, 5, 0, 2 * Math.PI)
        ctx.fill()
        ctx.stroke()
        this.$emit('change', x, y)
      }
      if (this.points && this.points.length > 0) {
        this.points.forEach(item => {
          const delt = (item.x - x) * (item.x - x) + (item.y - y) * (item.y - y)
          if (delt < 25) {
            this.$emit('position', item)
          }
        })
      }
    }
  }
}
</script>

<style scoped>
  .canvas-style {
    border: 1px solid #000000;
    -webkit-background-size: 100% 100%;
    background-size: 100% 100%;
  }
</style>
